package com.zb.validation;

import com.zb.annotation.NumberPattern;
import com.zb.utils.VerificUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @Author WEN
 * @Date 2023/8/2 0002
 **/
public class NumberValidator implements ConstraintValidator<NumberPattern, Number> {
    private String regexp;

    private boolean required;

    @Override
    public void initialize(NumberPattern constraintAnnotation) {
        // 赋值给全局变量
        this.regexp = constraintAnnotation.regexp();
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(Number val, ConstraintValidatorContext constraintValidatorContext) {
        // 必填的则校验
        if (this.required && Objects.isNull(val)) {
            return false;
        }
        // 不是必填则放行
        if (Objects.isNull(val)) {
            return true;
        }
        return Pattern.matches(this.regexp, val.toString());
    }

    public static void main(String[] args) {
//        String reg = "^[1-9]\\d{0,3}$";
//        String reg = "^([1-9]\\d{0,3})|([1-9]\\d{0,3})(\\.[0-9]{1,2})|0\\.([0-9]{1,2})$";
//        String reg = "^0?|([1-9]\\d{0,9})|([1-9]\\d{0,9})(\\.[0-9]{1,2})|0\\.([0-9]{1,2})$";
        String reg = "^0$|^[1-9]\\d{0,7}$|^[1-9]\\d{0,7}\\.\\d{1,2}$|^0\\.\\d{1,2}$";
//        String reg = "^0\\.\\d{1,2}$";
        System.out.println(Pattern.matches(reg, "123458"));
        System.out.println(Pattern.matches(reg, "12345678.08"));
        System.out.println(Pattern.matches(reg, "5.08"));
        System.out.println(Pattern.matches(reg, "0.08"));
    }
}
